use eframe::{App, egui};
use egui::{Color32, RichText};
fn main() -> eframe::Result {
    let mut options = eframe::NativeOptions::default();
    eframe::run_native(
        "你好世界",
        options,
        Box::new(|cc| Ok(Box::new(MyApp::default()))),
    )
}
#[derive(Default)]
struct MyApp {
    input: String,
    search: String,
    todos: Vec<Todo>,
    counter: i32,
}

struct Todo {
    id: i32,
    title: String,
    completed: bool,
}
impl MyApp {
    fn add_task(&mut self, title: String) {
        let todo = Todo {
            id: self.counter,
            title: title,
            completed: false,
        };
        self.counter += 1;
        self.todos.push(todo);
    }
    fn remove_task(&mut self, id: i32) {
        self.todos.retain(|todo| todo.id != id);
    }
}
impl App for MyApp {
    fn update(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
        let mut to_remove = Vec::new();
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.heading("Todo");
            ui.text_edit_singleline(&mut self.input);
            if ui.button("Add").clicked() && !self.input.is_empty() {
                let title = self.input.clone();
                self.input.clear();
                self.add_task(title);
            }
            ui.text_edit_singleline(&mut self.search);
            ui.separator();
            self.todos.iter_mut().for_each(|todo| {
                if !todo.title.contains(&self.search) {
                    return;
                }
                ui.horizontal(|ui| {
                    ui.checkbox(&mut todo.completed, "");

                    if todo.completed {
                        ui.label(RichText::new(&todo.title).italics());
                    } else {
                        ui.label(&todo.title);
                    }
                    if ui.button("X").clicked() {
                        to_remove.push(todo.id);
                    }
                });
            });
            to_remove.iter().for_each(|id| {
                self.remove_task(*id);
            });
        });
    }
}
